package com.rzico.market.receiver;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.rzico.account.model.Attach;
import com.rzico.market.service.PhoneOrderService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

/**
 * Created by icssh on 2020/1/28.
 */
@Controller
@Slf4j
public class PhonePaymentReceiver implements ChannelAwareMessageListener {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private PhoneOrderService phoneOrderService;


    @Override
    @RabbitHandler
    @RabbitListener(queues = "queue.phoneOrder.phonePayment")
    public void onMessage(Message message, Channel channel) throws Exception {
        boolean success = false;
        try {

            //同一时刻服务器只会发送一条消息给消费者
            channel.basicQos(1);

            String str = new String(message.getBody());
            Attach attachQueue = JSON.parseObject(str,Attach.class);
            try {
                if ("0000".equals(attachQueue.getCode())) {
                    phoneOrderService.paymentHandle(Long.valueOf(attachQueue.getId()));
                }
                success = true;
            } catch (Exception e) {
                logger.error(str);
                logger.error(e.getMessage());
                success = false;
            }

        } finally {
            if (success) {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            } else {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            }
        }
    }

}
